<template>
  <div class="all">
    <header>
      <div class="div" @click="back">
        <img src="../../../assets/返回.png" alt="">
        <span class="solid">返回</span>
      </div>
      <div class="div">
        <span>血糖测量</span>
      </div>
      <div class="div">
        <span class="solid" @click="keep">保存</span>
      </div>
    </header>
    <van-field @click="datePicker =true"
      is-link arrow-direction="down"
               v-model="xueTangData.time" type="text"
               readonly placeholder="请选择测量时间"
               label="测量时间" input-align="right"  />
    <van-field @click="statePicker = true"
      is-link arrow-direction="down"
               v-model="xueTangData.choose_name" type="text"
               readonly placeholder="请选择测量时状态"
               label="测量时状态" input-align="right"  />
    <van-field v-model="xueTangData.content" type="number"
               placeholder="请输入血糖值"
               label="血糖值" input-align="right"  >
      <template #right-icon>
        <span style="color: #333333">mmol/L</span>
      </template>
    </van-field>

    <van-collapse  v-model="activeNames">
      <van-collapse-item style="margin-top: 5px" name="1">
        <template #title>
          <div style="display: flex;align-items: center">
            <a class="hengGang"></a>
            治疗计划
          </div>
        </template>
      <div class="box" v-for="(item, index) in xueTangData.treatArr" :key="index">
        <div class="title" @click="id ? '' : addTreat(item)">
          {{item.title}}
          <img class="addImg" src="../../../assets/jia.png" alt="">
        </div>
        <van-row  v-for="(curr, currIndex) in item.list" :key="currIndex" type="flex" justify="space-between" align="center">
          <van-col span="19" style="margin: 5px 0;min-height: 29px;">
            <p class="backBlue box_text">{{curr.xt_name}}
              <span class="solid">{{curr.h_content}}{{unit(item)}}</span>
            </p>
          </van-col>
          <van-col span="4" @click="yaoPinSelect(curr, index)">
            <p style="display: flex;align-items: center">
              <img  v-if="curr.perfrom == 1"  class="selectImg" src="../../../assets/题目选择.png" alt="">
              <img v-else class="selectImg"  src="../../../assets/题目未选择.png" alt="">
              执行
            </p>
          </van-col>
        </van-row>
      </div>
    </van-collapse-item>
<!--    <van-collapse-item style="margin-top: 5px"  name="2">-->
<!--        <template #title>-->
<!--          <div style="display: flex;align-items: center">-->
<!--            <a class="hengGang"></a>-->
<!--            目前症状-->
<!--          </div>-->
<!--        </template>-->
<!--        <template #value>-->
<!--          <input type="text" v-model="xueTangData.symptoms">-->
<!--        </template>-->
<!--       -->
<!--      </van-collapse-item>-->
    </van-collapse>
    <van-field @click="symptomPicker = true"
               is-link
               arrow-direction="down"
               v-model="xueTangData.symptoms_name" type="text"
               readonly placeholder="请选择目前症状"
               label="目前症状" input-align="right"  >
      <template #label >
        <span  style="display: flex;align-items: center">
          <a class="hengGang"></a>
            目前症状
        </span>
      </template>
    </van-field>
    <div style="background: #FFFFFF;padding: 10px 0;box-sizing: border-box">
      <div class="textareaDiv">
        <textarea v-model="xueTangData.s_content"
                  placeholder="输入备注信息" maxlength="200" name="" id="" cols="30" rows="10"></textarea>
        <span >{{xueTangData.s_content.length}}/200</span>
      </div>
    </div>
    <div v-show="isLoading"
         style="width: 100%;height: 100%;display: flex;align-items: center;justify-content: center;position: absolute;top: 0;background: rgba(0, 0, 0, 0.5)" >
      <van-loading size="24px" type="spinner" color="#fff">保存中...</van-loading>
    </div>
    <van-popup v-model="datePicker" round position="bottom">
      <van-datetime-picker
        v-model="currentDate"
        type="datetime"
        title="选择年月日"
        :min-date="minDate"
        :max-date="maxDate"
        :formatter="formatter"
        @cancel="datePicker = false"
        @confirm="dateOnConfirm"
      />
    </van-popup>

    <van-popup v-model="statePicker" round position="bottom">
      <van-picker
        show-toolbar
        :columns="stateColumns"
        @cancel="statePicker = false"
        @confirm="stateOnConfirm"
      />
    </van-popup>
    <van-popup v-model="symptomPicker" round position="bottom">
      <van-picker
        show-toolbar
        :columns="symptomColumns"
        @cancel="symptomPicker = false"
        @confirm="symptomOnConfirm"
      />
    </van-popup>
    <van-dialog v-model="keepShow"
                width="80%"
                confirm-button-color="#1da4f2"
                title="确认保存吗？"
                @confirm="keepConfirm()"
                show-cancel-button>
    </van-dialog>

  </div>
</template>

<script>
export default {
  name: 'AddXueTang',
  data () {
    return {
      id: this.$route.query.id, // 新增传0，修改传对应的id
      userid: this.$route.query.userid, // 用户登陆的id
      activeNames: ['1', '2'],
      statePicker: false,
      stateColumns: [
        {
          text: '空腹',
          id: 0
        }, {
          text: '餐后1小时',
          id: 1
        }, {
          text: '餐后2小时',
          id: 2
        }, {
          text: '餐后3小时',
          id: 3
        }
      ],
      minDate: new Date(2000, 0, 1),
      maxDate: new Date(),
      currentDate: new Date(),
      datePicker: false,
      xueTangData: {
        content: '',
        time: '',
        choose_name: '',
        chooseid: '', // '0:空腹 1:餐后1小时 2:餐后2小时 3：餐后三小时'
        classification: 1, // '分类  1：手工 2：机器'
        symptoms_name: '', // 目前症状
        symptoms: '', // 目前症状
        s_content: '', // 目前症状输入框
        treatArr: [
          {
            title: '胰岛素/胰岛素类类似药物',
            xt_type: 1,
            list: []
          }, {
            title: '口服降糖药',
            xt_type: 2,
            list: []
          }, {
            title: '饮食',
            xt_type: 3,
            list: []
          }, {
            title: '运动',
            xt_type: '',
            list: []
          }
        ],
        index: 0
      },
      keepShow: false,
      symptomPicker: false,
      symptomColumns: [
        {
          text: '无不适',
          id: 0
        }, {
          text: '三多',
          id: 1
        }, {
          text: '乏力',
          id: 2
        }, {
          text: '腹痛呕吐',
          id: 3
        }, {
          text: '呼吸快',
          id: 4
        }, {
          text: '眼下限',
          id: 5
        }, {
          text: '头痛',
          id: 6
        }, {
          text: '昏迷',
          id: 7
        }, {
          text: '抽搐',
          id: 8
        }, {
          text: '出汗',
          id: 9
        }, {
          text: '饥饿',
          id: 10
        }, {
          text: '心悸',
          id: 11
        }
      ],
      isLoading: false
    }
  },
  computed: {
    unit () {
      return function (item) {
        let unit = ''
        if (item.xt_type == 1) {
          unit = 'U'
        } else if (item.xt_type == 2) {
          unit = '粒'
        } else if (item.xt_type == 3) {
          unit = 'g'
        }
        return unit
      }
    }
  },
  mounted () {
    if (sessionStorage.getItem('xueTangData')) {
      this.xueTangData = JSON.parse(sessionStorage.getItem('xueTangData'))
      if (this.xueTangData.time) {
        this.currentDate = new Date(this.xueTangData.time)
      }
    }
    if (this.id) {
      this.getHis()
    } else {
      this.getFindHealthXTweiHu()
    }
    this.xueTangData.index = 0
  },
  methods: {
    getHis () {
      this.$http.findHealthdataOneXT({id: this.id})
        .then(res => {
          console.log(res)
          if (res.data.status === 'success') {
            let data = res.data.data
            let obj = {
              content: data.content,
              time: data.time,
              choose_name: this.stateColumns[Number(data.chooseid)].text,
              chooseid: data.chooseid, // '0:空腹 1:餐后1小时 2:餐后2小时 3：餐后三小时'
              classification: 1, // '分类  1：手工 2：机器'
              symptoms_name: this.symptomColumns[data.symptoms].text, // 目前症状
              symptoms: data.symptoms, // 目前症状
              s_content: data.s_content, // 目前症状输入框
              treatArr: [
                {
                  title: '胰岛素/胰岛素类类似药物',
                  xt_type: 1,
                  list: data.YDlIST
                }, {
                  title: '口服降糖药',
                  xt_type: 2,
                  list: data.JTlIST
                }, {
                  title: '饮食',
                  xt_type: 3,
                  list: data.YSlIST
                }, {
                  title: '运动',
                  xt_type: '',
                  list: []
                }
              ],
              index: 0
            }
            this.xueTangData = obj
            console.log(obj)
          } else {
            this.$toast(res.data.msg)
          }
        })
        .catch(err => {
          console.log(err)
          this.$toast('您的网络有些拥挤，请稍后再试')
        })
    },
    // 当前状况  确认按钮
    symptomOnConfirm (value) {
      this.xueTangData.symptoms_name = value.text
      this.xueTangData.symptoms = value.id
      this.symptomPicker = false
    },
    // 确认保存  按钮
    keepConfirm () {
      this.isLoading = true
      let Glist = []
      this.xueTangData.treatArr.map((curr, index) => {
        curr.list.map((childen, childenIndex) => {
          let obj = {'perfrom': childen.perfrom, 'weihu_id': childen.id}
          if (childen.perfrom) {
            Glist.push(obj)
          }
        })
      })
      let data = {
        'id': 0,
        'userid': this.userid,
        'content': Number(this.xueTangData.content),
        'time': this.xueTangData.time,
        'chooseid': this.xueTangData.chooseid,
        'classification': this.xueTangData.classification,
        's_content': this.xueTangData.s_content,
        'Glist': Glist
      }
      if (this.xueTangData.symptoms_name !== '') {
        data.symptoms = Number(this.xueTangData.symptoms)
      }
      if (this.id) {
        data.id = this.id
      }
      this.$http.saveHealthdataXT(data)
        .then(res => {
          console.log(res)
          if (res.data.status === 'success') {
            this.keepShow = false
            sessionStorage.removeItem('xueTangData')
            this.getFindHealthXTweiHu()
            this.xueTangData.content = null
            this.$toast('保存成功')
            this.back()
          } else {
            this.$toast(res.data.msg)
          }
        })
        .catch(err => {
          console.log(err)
          this.$toast('您的网络有些拥挤，请稍后再试')
        })
      this.isLoading = false
    },
    // 保存
    keep () {
      let DH = this.xueTangData
      if (!DH.time) {
        this.$toast('请选择测量时间')
        return false
      } else if (!DH.choose_name) {
        this.$toast('请选择测量时状态')
        return false
      } else if (!DH.content) {
        this.$toast('请输入血糖值')
        return false
      } else if (!this.xueTangData.symptoms_name) {
        this.$toast('请选择目前症状')
        return false
      }
      this.keepShow = true
    },
    yaoPinSelect (item, index) {
      if (item.perfrom) {
        item.perfrom = !item.perfrom
      } else {
        this.$set(item, 'perfrom', 1)
      }
    },
    // 获取得到的治疗信息
    getFindHealthXTweiHu () {
      this.$http.findHealthXTweiHu({userid: this.userid})
        .then(res => {
          console.log(res)
          if (res.data.status === 'success') {
            let XT = res.data.data
            this.xueTangData.treatArr[0].list = XT.YdlIST
            this.xueTangData.treatArr[1].list = XT.JTlIST
            this.xueTangData.treatArr[2].list = XT.YSlIST
          } else {
            this.$toast(res.data.msg)
          }
        })
        .catch(err => {
          console.log(err)
          this.$toast('您的网络有些拥挤，请稍后再试')
        })
    },
    // 测量时间
    dateOnConfirm () {
      this.xueTangData.time = this.Common.formatDate(this.currentDate)
      this.datePicker = false
    },
    // 选择日期添加年月日
    formatter (type, val) {
      if (type === 'year') {
        return `${val}年`
      } else if (type === 'month') {
        return `${val}月`
      } else if (type === 'day') {
        return val + '日'
      } else if (type === 'hour') {
        return val + '点'
      } else if (type === 'minute') {
        return val + '分'
      }
      return val
    },
    // 选择 测量时状态 是餐后几小时
    stateOnConfirm (value) {
      this.xueTangData.chooseid = value.id
      this.xueTangData.choose_name = value.text
      this.statePicker = false
    },
    // 添加治疗计划
    addTreat (item) {
      if (item.xt_type) {
        sessionStorage.setItem('xueTangData', JSON.stringify(this.xueTangData))
        this.$router.push({path: '/SelectTreat', query: {xt_type: item.xt_type, userid: this.userid}})
      }
    },
    // 返回
    back () {
      this.$router.history.go(-1)
      // this.$router.push({path: '/health', query: {userid: this.userid}})
      sessionStorage.removeItem('xueTangData')
    }
  },
  destroyed () {
    // sessionStorage.removeItem('xueTangData')
  }
}
</script>

<style scoped>
.all{
  width: 100%;
  height: 100%;
  background: #FAF9FE;
  overflow: auto;
  font-size: 15px;
  font-family: PingFang SC;
}
header{
  width: 100%;
  height: 44px;
  display: flex;
  align-items: center;
  border-bottom: 1px solid #E5E5E5;
  background: white;
  position: sticky;
  top: 0;
  z-index: 9;
}
.div{
  width: 33%;
  height: 100%;
  display: flex;
  align-items: center;
  font-family: "PingFang SC";
  font-size: 15px;
  font-weight: bold;
}
.div img{
  margin-right: 5px;
}
.div:nth-child(1) img{
  height: 13px;
  width: 7px;
  margin-left: 15px;
}
.div:nth-child(3) img{
  margin-right: 5px;
  width: 13px;
  height: 13px;
}
.div:nth-child(3) span{
  margin-right: 15px;
}
.div:nth-child(2){
  justify-content: center;
}
.div:nth-child(3){
  justify-content: flex-end;
}
.solid{
  color: #1DA4F2;
}
.hengGang{
  width: 2px;
  height: 15px;
  background: #1da4f2;
  display: block;
  margin-right: 5px;
  border-radius: 2px;
}
.box {
  border-bottom: 1px solid #E5E5E5;
  /*padding: 5px 0;*/
  box-sizing: border-box;
}
.title {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: space-between;
  color: #333333;
  height: 44px;
}
.addImg{
  width: 22px;
  height: 22px;
}
.backBlue{
  background: #E8F6FE;
}
.box_text{
  border-radius: 5px;
  padding: 5px;
  box-sizing: border-box;
  color: #333333;
}
.selectImg{
  width: 16px;
  height: 16px;
  margin-right: 5px;
}
.textareaDiv{
  width: 95%;
  height: 130px;
  background: #FAF9FE;
  border: 1px solid #999999;
  border-radius: 20px;
  overflow: hidden;
  color: #333333;
  margin: 5px auto;
}
.textareaDiv span{
  display: flex;
  justify-content: flex-end;
  margin-right: 10px;
}
.textareaDiv textarea{
  resize: none;
  width: 100%;
  height: 80%;
  padding: 10px;
  box-sizing: border-box;
  border: none;
  background: transparent;
}
input{
  border: none;
  text-align: center;
}
/deep/ .van-cell{
  font-size: 15px;
}
</style>
